package org.boxsql.logEngine;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class LogEngine {

   public void logMessage(final String message, final String fileName, final String prefix) {
      try {
         StringBuilder sb = new StringBuilder();
         try {
            sb.append(readFile(fileName));
            sb.append("\n # " + prefix + " - " + new Date().toString() + " # \n");
         } finally {
            sb.append(message);
         }
         final BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
         out.write(sb.toString());
         out.close();
         sb = null;
      } catch (final IOException e) {
         e.printStackTrace();
      }
   }

   public String readFile(final String fileName) {
      String str;
      final StringBuffer s = new StringBuffer();
      try {
         final BufferedReader in = new BufferedReader(new FileReader(fileName));
         while ((str = in.readLine()) != null) {
            s.append(str + '\n');
         }
         in.close();
      } catch (final IOException e) {
         e.printStackTrace();
      }
      return s.toString();
   }
}
